﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net.NetworkInformation;
using Server_Monitor.Controllers;
using Server_Monitor.Domain;
namespace Server_Monitor.Forms
{
    public partial class Monitor : Form
    {
        public bool RestartWork = false;
        public Monitor()
        {
            InitializeComponent();
        }

        private void Monitor_Load(object sender, EventArgs e)
        {
            bkgWorker.RunWorkerAsync(ServerController.GetServers());
            LoadServerGrid();
        }
        private void LoadServerGrid()
        {
            dgServers.DataSource = null;
            dgServers.DataSource = ServerController.GetServers();
        }

        private void bkgWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            List<Server> servers = (List<Server>)e.Argument;
            while (!bkgWorker.CancellationPending)
            {
                foreach (Server server in servers)
                {
                    try
                    {
                        Ping _ping = new Ping();
                        server.PingSuccess = (_ping.Send(server.ServerIP, 200).Status == IPStatus.Success);
                    }
                    catch
                    {
                        server.PingSuccess = false;
                    }
                }
                bkgWorker.ReportProgress(10, servers);
                Thread.Sleep(Program.POOL_TIME);
            }
        }

        private void bkgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (RestartWork)
            {
                RestartWork = false;
                bkgWorker.RunWorkerAsync(ServerController.GetServers());
            }
        }

        private void bkgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            dgServers.DataSource = null;
            dgServers.DataSource = (List<Server>)e.UserState;
            lblDateTIme.Text = "Pooling Period : " + Program.POOL_TIME_IN_SECONDS + " Seconds." + " Last Update : " + DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString();
        }

        private void dgServers_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.ColumnIndex != 1)
                return;
            if (!((Server)dgServers.Rows[e.RowIndex].DataBoundItem).PingSuccess)
            {
                dgServers.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red;
            }
            else
            {
                dgServers.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Green;
            }
        }
    }
}
